<?php

namespace app\controller;

use think\swoole\WebSocket;

class Chat
{

    public function onOpen(WebSocket $websocket, $request)
    {

        // 当有新的 WebSocket 连接时触发
        $fd = $request->fd;
//        echo "客户端{$fd}连接成功\n";
        $websocket->emit('message', "Welcome to {$fd} the chat room!");
    }

    public function onMessage(WebSocket $websocket, $frame)
    {
        // 当收到消息时触发
        $data = json_decode($frame->data, true);
        $message = $data['message'] ?? '';

        // 广播消息给所有连接的客户端
        $websocket->broadcast()->emit('message', [
            'user' => $frame->fd,
            'message' => $message,
        ]);
    }

    public function onClose(WebSocket $websocket, $fd)
    {
        // 当连接关闭时触发
        $websocket->broadcast()->emit('message', "User {$fd} has left the chat.");
    }
}